package k5_net.demo02;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TCPClientDouble {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        try {
            Socket socket = new Socket("localhost",8888);
            System.out.println("客户端已经成功连接服务端");

            //把客户端的内容封装成字符打印输出流,向服务端写数据
            PrintWriter pw = new PrintWriter(socket.getOutputStream());

            //通过socket获取数据的输入流
            InputStream is = socket.getInputStream();
            //把InputStream流通过转换流，编程字符流
            InputStreamReader isr = new InputStreamReader(is);
            //再对字符流进行封装成缓冲流,用于读取服务端的数据
            BufferedReader br = new BufferedReader(isr);

            System.out.println("开始聊天了");

            new Thread(()->{
                while(true){
                    //从控制台读取信息
                    String message = scanner.nextLine();
                    pw.println(message);
                    pw.flush();
                }
            }).start();

            //创建一个读取客户端数据的线程
            new Thread(()->{
                try {
                    String line = "";
                    //循环读取客户端的输入内容
                    while((line=br.readLine())!=null){
                        System.out.println("服务端说："+line);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }).start();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
